package com.abgame.test.springdatajpa.demo.service.impl;

import com.abgame.test.springdatajpa.demo.dao.AccountDao;
import com.abgame.test.springdatajpa.demo.entity.Account;
import com.abgame.test.springdatajpa.demo.service.AccountService;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 用户表(Account)表服务实现类
 *
 * @author makejava
 * @since 2021-01-16 16:35:51
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountDao accountDao;

    @Override
    public Account queryById(Integer accountId) {
        Account account = this.accountDao.findById(accountId).orElse(null);
        return account;
    }

    @Override
    public List<Account> getall() {
        return this.accountDao.findAll();

    }

    @Override
    public Page<Account> queryAllByLimit(int offset, int limit) {
        return this.accountDao.findAll(PageRequest.of((offset - 1)
                * limit, limit));
    }

    @Override
    public Account insert(Account account) {

        return this.accountDao.saveAndFlush(account);
    }


    @Override
    public Account update(Account account) {

        return this.accountDao.save(account);
    }


    @Override
    public boolean deleteById(Integer accountId) {

        try {
            this.accountDao.deleteById(accountId);
        } catch (Exception ex) {
            return false;
        }
        return true;

    }

    @Override
    public int modify(Account account) {
     //   return this.accountDao.modifyWithHql(account);
        return this.accountDao.modifyWithSQL(account);
    }

    @Override
    public int deleteAccount(Account account) {
        accountDao.deleteById(account.getAccountId());

        return 0;
    }

    @Override
    public Account getAccountByName(String name) {
        Account account = new Account();
        account.setAccountName(name);
        account.setAgentId(1);
        Example<Account> example = Example.of(account);
        Account queryAccount = accountDao.findOne(example).orElse(null);

        return queryAccount;
    }

    @Override
    public Page<Account> pageAccount(Integer pageNum) {
        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "accountId");
        Pageable pageable = PageRequest.of(pageNum-1, 2, sort);

        Account account = new Account();
        account.setAgentId(1);
        Example<Account> example = Example.of(account);

        Page<Account> page = accountDao.findAll(example, pageable);
        return page;
    }
}